CC = riscv64-unknown-elf-gcc
LD = riscv64-unknown-elf-ld
OBJDUMP = riscv64-unknown-elf-objdump

CFLAGS = -Wall -O0 -ggdb
CFLAGS += -ffreestanding -nostdlib -nostartfiles
CFLAGS += -march=rv64gc -mabi=lp64
CFLAGS += -Iinclude
CFLAGS += -fno-pic -mcmodel=medany

KERNEL_SRCS = \
	kernel/boot/entry.S \
	kernel/boot/start.c \
	kernel/drivers/uart.c \
	kernel/lib/printf.c

KERNEL_OBJS = $(KERNEL_SRCS:.c=.o)
KERNEL_OBJS := $(KERNEL_OBJS:.S=.o)

all: kernel.elf

kernel.elf: $(KERNEL_OBJS) kernel.ld
	$(LD) -T kernel.ld -o $@ $(KERNEL_OBJS)
	@echo "=== 实验2构建成功 ==="
	$(OBJDUMP) -S $@ > kernel.asm
	$(OBJDUMP) -t $@ > kernel.sym

%.o: %.S
	$(CC) $(CFLAGS) -c -o $@ $<

%.o: %.c
	$(CC) $(CFLAGS) -c -o $@ $<

qemu: kernel.elf
	@echo "=== 启动QEMU测试 ==="
	qemu-system-riscv64 -machine virt -bios none -kernel kernel.elf -nographic

clean:
	rm -f $(KERNEL_OBJS) kernel.elf kernel.asm kernel.sym
	@echo "=== 清理完成 ==="

info: kernel.elf
	@echo "=== 内核信息 ==="
	file kernel.elf
	@echo "=== 主要符号 ==="
	$(OBJDUMP) -t kernel.elf | grep -E "(main|printf|clear_screen|test_)"

.PHONY: all qemu clean info